package com.tplhk.security.controller.charter11;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


@Service
public class HelloService11 {
    @PreAuthorize("principal.username.equals('user')")
    public String hello() {
        return "hello-user";
    }

    @PreAuthorize("hasAnyAuthority('admin')")
    public String admin() {
        return "hello-admin";
    }

    /**
     * 参数 age>98 才能访问
     *
     * @param age
     * @return
     */
    @PreAuthorize("#age>98")
    public String getAge(Integer age) {
        return String.valueOf(age);
    }

    /**
     * 方法执行后过滤结果
     *
     * @return [
     * "javaboy:2"
     * ]
     */
    @PostFilter("filterObject.lastIndexOf('2')!=-1")
    public List<String> getAllUser() {
        List<String> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            users.add("javaboy:" + i);
        }
        return users;
    }

    /**
     * PreFilter: 方法执行前，过滤参数
     * 入参
     * {
     * "ages":[1,2,3,4,5,6],
     * "users":["a","b","c","d"]
     * }
     * 返回：
     * ages = [2, 4, 6]
     * users = [a, b, c, d]
     */
    @PreFilter(filterTarget = "ages", value = "filterObject%2==0")
    public void getAllAge(List<Integer> ages, List<String> users) {
        System.out.println("ages = " + ages);
        System.out.println("users = " + users);
    }
}
